import { defineStore } from "pinia"
import { Message } from "@arco-design/web-vue";


export const userpinia = defineStore("userpinia", {
  state: () => ({
    userinfo: {} as any,
    money: 0,
    token: useCookie("userToken") || ''
  }),
  getters: {
    // 未读消息数
    // unreadTotal(state) {
    //   return state.notificationNumber6
    // }
  },
  actions: {

    // 获取用户信息
    async getUserinfo() {
      const router = useRouter();
      const route = useRoute();
      if (!this.token) return
      const res: any = await yujiRequest('/user/getUserInfo', { method: 'POST' })
      if (res.code == 1) {
        if (process.client) {
          const cookies = useCookie("userToken")
          cookies.value = res.data.token
          const userInfo = useCookie("userInfo")
          userInfo.value = res.data
          this.userinfo = userInfo.value
          if(route.fullPath == '/login' || route.fullPath == '/register') {
            router.push("/")
          }
        }

      }else{
        if (process.client) {
          const cookies = useCookie("userToken")
          cookies.value = ''
          const userInfo = useCookie("userInfo")
          userInfo.value = null
          this.userinfo = {}
          return Message.error('TOKEN失效，请重新登录')
        }
      }
      // if (res.status !== 200) {
      //   if (process.client) {
      //     // 删除TOKEN 清楚COOKIE
      //     this.userinfo = {}
      //     this.token = ''
      //     const cookie = useCookie("CNYZSTOKEN", { sameSite: "strict" })
      //     cookie.value = undefined
      //     return Message.error(res.message)
      //   }
      // } else {
      //   if (res.data) {
      //     this.userinfo = res.data
      //     this.money = res.data.money
      //   } else {
      //     if (process.client) {
      //       // 删除TOKEN 清楚COOKIE
      //       this.userinfo = {}
      //       this.token = ''
      //       const cookie = useCookie("CNYZSTOKEN", { sameSite: "strict" })
      //       cookie.value = undefined
      //
      //       return Message.error('TOKEN失效，请重新登录')
      //     }
      //   }
      // }
    },

    // 退出登录
    async outlogin() {
      this.userinfo = {}
      this.token = ''
      const cookie = useCookie("CNYZSTOKEN", { sameSite: "strict" })
      cookie.value = undefined
      Message.success('退出成功')
      // window.open('/', "_self")
    },


  },
})